package com.yupi.springbootinit.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.annotation.OperationLog;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.DeleteRequest;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.model.dto.user.*;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.vo.LoginUserVO;
import com.yupi.springbootinit.model.vo.UserVO;
import com.yupi.springbootinit.model.vo.UserStatisticsVO;
import com.yupi.springbootinit.model.vo.DepartmentUserStatVO;
import com.yupi.springbootinit.service.UserService;
import com.yupi.springbootinit.service.DepartmentService;
import com.yupi.springbootinit.model.entity.Department;

import java.beans.FeatureDescriptor;
import java.util.Arrays;
import java.util.List;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.DigestUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import static com.yupi.springbootinit.service.impl.UserServiceImpl.SALT;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private DepartmentService departmentService;


    // region 登录相关

    /**
     * 用户注册
     *
     * @param userRegisterRequest 用户注册请求
     * @return 新用户ID
     */
    @PostMapping("/register")
    @OperationLog(module = "用户管理", operation = "注册", description = "用户注册", recordParams = true, recordResult = true)
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userName = userRegisterRequest.getUserName();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        Long departmentId = userRegisterRequest.getDepartmentId();
        if (StringUtils.isAnyBlank(userAccount, userName, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        long result = userService.userRegister(userAccount, userName, userPassword, checkPassword, departmentId);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest 用户登录请求
     * @param request HTTP请求
     * @return 登录用户信息
     */
    @PostMapping("/login")
    @OperationLog(module = "用户管理", operation = "登录", description = "用户登录", recordParams = false, recordResult = true)
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 用户注销
     *
     * @param request HTTP请求
     * @return 注销结果
     */
    @PostMapping("/logout")
    @OperationLog(module = "用户管理", operation = "注销", description = "用户注销登录", recordParams = false)
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户
     *
     * @param request HTTP请求
     * @return 当前登录用户信息
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }

    // endregion

    // region 增删改查

    /**
     * 创建用户
     *
     * @param userAddRequest 用户创建请求
     * @param request HTTP请求
     * @return 新用户ID
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @OperationLog(module = "用户管理", operation = "新增", description = "管理员创建用户", recordParams = true, recordResult = true)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        userService.validateAdminUser(user, true);
        // 默认密码 12345678
        String defaultPassword = "12345678";
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + defaultPassword).getBytes());
        user.setUserPassword(encryptPassword);
        boolean result = userService.save(user);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "创建用户失败");
        }
        return ResultUtils.success(user.getId());
    }

    /**
     * 删除用户
     *
     * @param deleteRequest 删除请求
     * @param request HTTP请求
     * @return 删除结果
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @OperationLog(module = "用户管理", operation = "删除", description = "管理员删除用户", recordParams = true, recordDataChange = true)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 管理员删除用户：改为将用户迁移到“未分配”部门（不物理删除）
        Department unassignedDept = departmentService.getOrCreateUnassignedDepartment();
        User updateUser = new User();
        updateUser.setId(deleteRequest.getId());
        updateUser.setDepartmentId(unassignedDept.getId());
        boolean result = userService.updateById(updateUser);
        return ResultUtils.success(result);
    }

    /**
     * 更新用户
     *
     * @param userUpdateRequest 用户更新请求
     * @param request HTTP请求
     * @return 更新结果
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @OperationLog(module = "用户管理", operation = "更新", description = "管理员更新用户信息", recordParams = true, recordDataChange = true, primaryKeyField = "id",recordResult = true)
    public BaseResponse<Boolean> updateUser(@RequestBody @Valid UserUpdateRequest userUpdateRequest,
                                            HttpServletRequest request) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 获取并合并用户数据
        User originalUser = userService.getById(userUpdateRequest.getId());
        if (originalUser == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        BeanUtils.copyProperties(userUpdateRequest, originalUser, getNullPropertyNames(userUpdateRequest));

        userService.validateAdminUser(originalUser, false);
        boolean result = userService.updateById(originalUser);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新用户信息失败");
        }
        return ResultUtils.success(true);
    }

    // 辅助方法：获取空属性名数组
    private String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        return Arrays.stream(src.getPropertyDescriptors())
                .map(FeatureDescriptor::getName)
                .filter(name -> src.getPropertyValue(name) == null)
                .toArray(String[]::new);
    }

    /**
     * 根据 id 获取用户（仅管理员）
     *
     * @param id 用户ID
     * @param request HTTP请求
     * @return 用户信息
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     *
     * @param id 用户ID
     * @param request HTTP请求
     * @return 用户VO信息
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(long id, HttpServletRequest request) {
        BaseResponse<User> response = getUserById(id, request);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param userQueryRequest 用户查询请求
     * @param request HTTP请求
     * @return 用户分页列表
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<User>> listUserByPage(@RequestBody UserQueryRequest userQueryRequest,
                                                   HttpServletRequest request) {
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        return ResultUtils.success(userPage);
    }

    /**
     * 分页获取用户封装列表
     *
     * @param userQueryRequest 用户查询请求
     * @param request HTTP请求
     * @return 用户VO分页列表
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest,
                                                       HttpServletRequest request) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        // 限制爬虫
        if (size > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "分页大小不能超过20");
        }
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current, size, userPage.getTotal());
        List<UserVO> userVO = userService.getUserVO(userPage.getRecords());
        userVOPage.setRecords(userVO);
        return ResultUtils.success(userVOPage);
    }

    // endregion

    /**
     * 更新个人信息
     *
     * @param userUpdateMyRequest 个人信息更新请求
     * @param request HTTP请求
     * @return 更新结果
     */
    @PostMapping("/update/my")
    @OperationLog(module = "用户管理", operation = "修改", description = "用户修改个人信息", recordParams = true, recordDataChange = true, primaryKeyField = "id")
    public BaseResponse<Boolean> updateMyUser(@RequestBody UserUpdateMyRequest userUpdateMyRequest,
                                              HttpServletRequest request) {
        if (userUpdateMyRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        User user = new User();
        BeanUtils.copyProperties(userUpdateMyRequest, user);
        user.setId(loginUser.getId());
        boolean result = userService.updateById(user);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新个人信息失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 修改当前用户密码
     *
     * @param userUpdateMyPasswordRequest 密码修改请求
     * @param request HTTP请求
     * @return 修改结果
     */
    @PostMapping("/update/password")
    @OperationLog(module = "用户管理", operation = "修改", description = "用户修改密码", recordParams = false)
    public BaseResponse<Boolean> updateMyPassword(@RequestBody UserUpdateMyPasswordRequest userUpdateMyPasswordRequest,
                                                  HttpServletRequest request) {
        if (userUpdateMyPasswordRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = userService.updateMyPassword(loginUser, userUpdateMyPasswordRequest);
        return ResultUtils.success(result);
    }

    /**
     * 管理员手动解锁用户账户
     *
     * @param userAccount 用户账户
     * @return 解锁结果
     */
    @PostMapping("/admin/unlock")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @OperationLog(module = "用户管理", operation = "解锁", description = "管理员解锁用户账户", recordParams = true)
    public BaseResponse<Boolean> unlockUser(@RequestParam String userAccount) {
        if (StringUtils.isBlank(userAccount)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账户不能为空");
        }
        boolean result = userService.unlockUser(userAccount);
        return ResultUtils.success(result);
    }

    /**
     * 获取用户统计信息（仅管理员）
     *
     * @return 用户统计信息
     */
    @GetMapping("/statistics")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<UserStatisticsVO> getUserStatistics() {
        UserStatisticsVO statistics = userService.getUserStatistics();
        return ResultUtils.success(statistics);
    }

    /**
     * 获取各部门用户统计信息（仅管理员）
     *
     * @return 各部门用户统计列表
     */
    @GetMapping("/statistics/department")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<List<DepartmentUserStatVO>> getDepartmentUserStatistics() {
        List<DepartmentUserStatVO> statistics = userService.getDepartmentUserStatistics();
        return ResultUtils.success(statistics);
    }

    // region 部门负责人用户管理

    /**
     * 部门负责人创建用户（仅限本部门）
     *
     * @param userAddRequest 用户创建请求
     * @param request HTTP请求
     * @return 新用户ID
     */
    @PostMapping("/dept/add")
    @AuthCheck(mustRole = UserConstant.DEPT_LEADER_ROLE)
    @OperationLog(module = "用户管理", operation = "新增", description = "部门负责人创建用户", recordParams = true, recordResult = true)
    public BaseResponse<Long> addUserByDeptLeader(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        User loginUser = userService.getLoginUser(request);
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        
        // 强制设置为当前部门负责人所在部门
        user.setDepartmentId(loginUser.getDepartmentId());
        // 强制设置为普通用户角色
        user.setUserRole(UserConstant.DEFAULT_ROLE);
        
        userService.validateAdminUser(user, true);
        
        // 默认密码 12345678
        String defaultPassword = "12345678";
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + defaultPassword).getBytes());
        user.setUserPassword(encryptPassword);
        
        boolean result = userService.save(user);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "创建用户失败");
        }
        return ResultUtils.success(user.getId());
    }

    /**
     * 部门负责人删除用户（仅限本部门普通用户）
     *
     * @param deleteRequest 删除请求
     * @param request HTTP请求
     * @return 删除结果
     */
    @PostMapping("/dept/delete")
    @AuthCheck(mustRole = UserConstant.DEPT_LEADER_ROLE)
    @OperationLog(module = "用户管理", operation = "删除", description = "部门负责人删除用户", recordParams = true, recordDataChange = true)
    public BaseResponse<Boolean> deleteUserByDeptLeader(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        User loginUser = userService.getLoginUser(request);
        
        // 检查是否有权限管理该用户
        if (!userService.canManageUser(loginUser, deleteRequest.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限删除该用户");
        }
        
        // 将用户迁移到“未分配”部门（不物理删除）
        Department unassignedDept = departmentService.getOrCreateUnassignedDepartment();
        User updateUser = new User();
        updateUser.setId(deleteRequest.getId());
        updateUser.setDepartmentId(unassignedDept.getId());
        boolean result = userService.updateById(updateUser);
        return ResultUtils.success(result);
    }

    /**
     * 部门负责人更新用户（仅限本部门普通用户）
     *
     * @param userUpdateRequest 用户更新请求
     * @param request HTTP请求
     * @return 更新结果
     */
    @PostMapping("/dept/update")
    @AuthCheck(mustRole = UserConstant.DEPT_LEADER_ROLE)
    @OperationLog(module = "用户管理", operation = "更新", description = "部门负责人更新用户信息", recordParams = true, recordDataChange = true, primaryKeyField = "id", recordResult = true)
    public BaseResponse<Boolean> updateUserByDeptLeader(@RequestBody @Valid UserUpdateRequest userUpdateRequest,
                                                        HttpServletRequest request) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        User loginUser = userService.getLoginUser(request);
        
        // 检查是否有权限管理该用户
        if (!userService.canManageUser(loginUser, userUpdateRequest.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限修改该用户");
        }
        
        // 获取并合并用户数据
        User originalUser = userService.getById(userUpdateRequest.getId());
        if (originalUser == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        
        // 记录原始角色，防止被请求体修改
        String preservedRole = originalUser.getUserRole();
        // 合并更新字段（忽略空值）
        BeanUtils.copyProperties(userUpdateRequest, originalUser, getNullPropertyNames(userUpdateRequest));
        // 强制为当前负责人所在部门，并还原角色，避免越权修改权限
        originalUser.setDepartmentId(loginUser.getDepartmentId());
        originalUser.setUserRole(preservedRole);
        
        userService.validateAdminUser(originalUser, false);
        boolean result = userService.updateById(originalUser);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新用户信息失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 部门负责人分页获取本部门用户列表
     *
     * @param userQueryRequest 用户查询请求
     * @param request HTTP请求
     * @return 用户分页列表
     */
    @PostMapping("/dept/list/page")
    @AuthCheck(mustRole = UserConstant.DEPT_LEADER_ROLE)
    public BaseResponse<Page<User>> listUserByPageForDeptLeader(@RequestBody UserQueryRequest userQueryRequest,
                                                                HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        
        // 使用部门负责人专用的查询条件
        QueryWrapper<User> queryWrapper = userService.getDeptLeaderQueryWrapper(loginUser, userQueryRequest);
        Page<User> userPage = userService.page(new Page<>(current, size), queryWrapper);
        
        return ResultUtils.success(userPage);
    }

    /**
     * 部门负责人分页获取本部门用户封装列表
     *
     * @param userQueryRequest 用户查询请求
     * @param request HTTP请求
     * @return 用户VO分页列表
     */
    @PostMapping("/dept/list/page/vo")
    @AuthCheck(mustRole = UserConstant.DEPT_LEADER_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPageForDeptLeader(@RequestBody UserQueryRequest userQueryRequest,
                                                                    HttpServletRequest request) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        User loginUser = userService.getLoginUser(request);
        
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        
        // 限制爬虫
        if (size > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "分页大小不能超过20");
        }
        
        // 使用部门负责人专用的查询条件
        QueryWrapper<User> queryWrapper = userService.getDeptLeaderQueryWrapper(loginUser, userQueryRequest);
        Page<User> userPage = userService.page(new Page<>(current, size), queryWrapper);
        
        Page<UserVO> userVOPage = new Page<>(current, size, userPage.getTotal());
        List<UserVO> userVO = userService.getUserVO(userPage.getRecords());
        userVOPage.setRecords(userVO);
        
        return ResultUtils.success(userVOPage);
    }

    // endregion

}
